import itchat
from itchat.content import *
import sys
import logging

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class WeChatBot:
    def __init__(self):
        try:
            # 初始化机器人
            print("微信机器人初始化中...")
            # 尝试使用较为安全的登录方式
            itchat.auto_login(
                hotReload=True,
                statusStorageDir='wechat.pkl',
                picDir='login_qr.png',
                enableCmdQR=2,  # 改为命令行显示二维码
                loginCallback=self.login_callback,
                exitCallback=self.exit_callback
            )
            print("微信机器人初始化成功！")
        except Exception as e:
            logger.error(f"初始化失败: {str(e)}")
            logger.error(f"Python版本: {sys.version}")
            logger.error(f"itchat版本: {itchat.__version__}")
            raise
    
    def login_callback(self):
        """登录成功的回调"""
        print("登录成功！")
    
    def exit_callback(self):
        """退出的回调"""
        print("已退出登录")
    
    def auto_reply(self):
        """设置自动回复规则"""
        # 注册私聊文本消息回复
        @itchat.msg_register([TEXT], isFriendChat=True)
        def reply_friends(msg):
            try:
                # 这里可以根据需要自定义回复规则
                if '你好' in msg['Text']:
                    return '你好！我是自动回复机器人'
                elif '再见' in msg['Text']:
                    return '再见！祝您有愉快的一天'
                else:
                    return f'收到您的消息：{msg["Text"]}\n(这是自动回复)'
            except Exception as e:
                logger.error(f"私聊回复出错: {str(e)}")
                return "消息处理出错，请稍后重试"
        
        # 注册群聊消息回复
        @itchat.msg_register([TEXT], isGroupChat=True)
        def reply_groups(msg):
            try:
                # 如果有人在群里@我
                if msg['IsAt']:
                    return f'收到@消息：{msg["Text"]}\n(这是自动回复)'
            except Exception as e:
                logger.error(f"群聊回复出错: {str(e)}")
                return "消息处理出错，请稍后重试"
    
    def run(self):
        """运行机器人"""
        try:
            self.auto_reply()
            # 开始运行
            itchat.run()
        except KeyboardInterrupt:
            print("\n退出微信机器人")
        except Exception as e:
            logger.error(f"运行出错: {str(e)}")
        finally:
            # 确保正确退出
            try:
                itchat.logout()
            except:
                pass

if __name__ == "__main__":
    try:
        print("启动微信自动回复机器人...")
        wechat_bot = WeChatBot()
        wechat_bot.run()
    except Exception as e:
        logger.error(f"程序异常退出: {str(e)}")
        sys.exit(1)

